Skip to content

Allow SWR mutation in useUser hook #2045

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
Open

Conversation

tusharpandey13
Copy link
Contributor

@tusharpandey13 tusharpandey13 commented Apr 7, 2025

Fixes: #1937

Changes

  • Added an invalidate function to the return value of the useUser hook.
  • This function allows developers to manually trigger a re-validation (re-fetch) of the user profile data from the /auth/profile endpoint.

Testing

Tests have been updated in src/client/hooks/use-user.test.tsx to cover the new invalidate functionality, ensuring it correctly triggers a data refresh using SWR's mutate function.

PASSING

Test Files  12 passed (12)
      Tests  180 passed | 4 skipped (184)
   Start at  15:39:08
   Duration  2.18s (transform 608ms, setup 0ms, collect 2.46s, tests 619ms, environment 816ms, prepare 2.13s)

Usage

Client Components:

You can access the invalidate function from the useUser hook and call it when you need to refresh the user data, for example, after a user profile update action.

"use client";

import { useUser } from '@auth0/nextjs-auth0/client';

export default function ProfileUpdater() {
  const { user, error, isLoading, invalidate } = useUser();

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>{error.message}</div>;

  const handleUpdateProfile = async () => {
    // Perform profile update logic...
    // const response = await fetch('/api/update-profile', { method: 'POST', ... });

    // After successful update, invalidate the user cache to refetch
    // invalidate(); // <--- Call invalidate here
    // Or use mutate directly if you have the updated user data
    // invalidate(updatedUserData, false); // Update local data immediately, don't revalidate
  };

  return (
    user && (
      <div>
        <h1>Welcome {user.name}!</h1>
        <button onClick={handleUpdateProfile}>Update Profile & Refresh</button>
      </div>
    )
  );
}

@tusharpandey13 tusharpandey13 requested a review from a team as a code owner April 7, 2025 12:18
@codecov-commenter
Copy link

codecov-commenter commented Apr 7, 2025

Codecov Report

Attention: Patch coverage is 82.75862% with 5 lines in your changes missing coverage. Please review.

Project coverage is 80.02%. Comparing base (dbfd502) to head (e6967b5).

Files with missing lines Patch % Lines
src/server/session/stateless-session-store.ts 50.00% 5 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2045      +/-   ##
==========================================
+ Coverage   78.47%   80.02%   +1.55%     
==========================================
  Files          21       21              
  Lines        1909     1907       -2     
  Branches      307      315       +8     
==========================================
+ Hits         1498     1526      +28     
+ Misses        405      376      -29     
+ Partials        6        5       -1     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@tusharpandey13 tusharpandey13 changed the title feature/mutateUserSWR Allow SWR mutation in useUser hook Apr 15, 2025
@tusharpandey13 tusharpandey13 dismissed frederikprijck’s stale review April 16, 2025 10:10

This has been taken care of

Copy link

@Copilot Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull Request Overview

This PR adds an invalidate function to the useUser hook to allow clients to manually trigger a SWR revalidation of the user profile. In addition, the PR includes various style and formatting improvements and updates to related tests to ensure full coverage of the new functionality.

  • Added an invalidate method to the useUser hook.
  • Updated both unit and integration tests to verify the correct behavior of invalidate.
  • Made minor formatting and code style adjustments across several session and auth client files.

Reviewed Changes

Copilot reviewed 12 out of 12 changed files in this pull request and generated no comments.

Show a summary per file
File Description
src/server/session/stateless-session-store.ts Refactored import and formatting of cookie decryption and cookie deletion.
src/server/session/stateless-session-store.test.ts Updated cookie name quoting and test formatting for clarity.
src/server/session/stateful-session-store.test.ts Cleaned up extra whitespace and standardized argument ordering.
src/server/cookies.ts Simplified arrow function syntax while preserving functionality.
src/server/auth-client.ts Reordered some error imports and formatted promise return type declarations.
src/server/auth-client.test.ts Adjusted bracket notation for property access and test callback formatting.
src/client/hooks/use-user.unit.test.tsx Added unit tests to cover the new invalidate functionality and revised SWR mocks.
src/client/hooks/use-user.ts Extended useUser to include invalidate using mutate and re-ordered error/data checks.
src/client/hooks/use-user.integration.test.tsx Introduced integration tests to validate re-fetch behavior and error handling on invalidate.

Comment on lines +83 to +86
// Call invalidate to trigger re-fetch
await act(async () => {
result.current.invalidate();
});
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When the user calls invalidate, it is going to call the URL again, is that correct? If yes, what is the reasoning for naming this invalidate, rather than refresh or so ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Issue: Need Client-side Session Cache Refresh Mechanism for Auth0 NextJS SDK v4
4 participants